#include <QScreen>
#include <QTimer>
#include <QFileInfo>
#include <QSettings>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "logger.h"
#include "realplay.h"
static EnvDispServer env_disp_server;       //画框回调用

#define SCREEN_WIDTH    (1080)
#define SCREEN_HEIGHT   (1920)


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    t = new QTimer(this);

    ui->setupUi(this);
    loadSysIni();

    /*1、设置背景颜色*/
    QPalette  palette;
    palette.setColor(QPalette::Window,QColor(255, 255, 255));
    this->setPalette(palette);

    /*2、海康sdk初始化*/
    if(init_haikang_sdk() == -1){
        LOG(ERROR) << "init haikang sdk err!"<< std::endl;
        assert(0);
    }
    /*3、 Web初始化*/
    init_web_view();

    /*4、 PIC 显示*/
    init_pic_view();

    /*5、 video 绘图*/
    init_video_draw();

    env_disp_server.init();
}

MainWindow::~MainWindow()
{
    delete ui;
}

//叠加字符回调函数
HBRUSH hbrush_hollow;
HPEN hpen_red;
HPEN hpen_green;
bool bInit =false;
void CALLBACK stringCallBack(LONG IRealPlayHandle ,HDC hdc , DWORD dwuser)
{
//    g_rectHideAlarmShow = {0, 0 ,200 ,50 };
//    ::DrawEdge(hdc,&g_rectHideAlarmShow,BDR_SUNKENOUTER,BF_RECT);
//  DrawText(hdc, TEXT("2"), -1, &g_rectHideAlarmShow, DT_VCENTER | DT_CENTER | DT_SINGLELINE);
//  SetBkMode(hdc,TRANSPARENT);

#if 0
    RECT g_rectHideAlarmShow = {0, 0 , 200 , 200};
    HBRUSH hbrush1 = (HBRUSH)GetStockObject(HOLLOW_BRUSH);
    //HBRUSH hbrush1 = (HBRUSH)GetStockObject(NULL_BRUSH);
    HPEN hpen1 = CreatePen(PS_SOLID, 3, RGB(0, 0, 255)); // 创建蓝色3像素宽度的实线画笔
    HPEN hpen_old = (HPEN)SelectObject(hdc, hpen1);      // 使用画笔
    HBRUSH hbrush_old = (HBRUSH)SelectObject(hdc, hbrush1);

    Rectangle(hdc, g_rectHideAlarmShow.left, g_rectHideAlarmShow.top, g_rectHideAlarmShow.right,g_rectHideAlarmShow.bottom);

    SelectObject(hdc, hpen_old);                         // 恢复原来的画笔和画刷
    SelectObject(hdc, hbrush_old);
#else
    std::vector <tagRECT> g_rects;
    std::vector <tagRECT> r_rects;
    qint64 millisecs;
    env_disp_server.get_rect(g_rects,r_rects,millisecs);
    qint64 current_millisecs = QDateTime::currentDateTime().toMSecsSinceEpoch();
 //   if((current_millisecs - millisecs)/1000 > 3){
 //       LOG(ERROR) << "Rects time out of range!";
 //       return;
 //   }

    //LOG(INFO) << "r_rects.size()" <<r_rects.size() <<std::endl;
    //LOG(INFO) << "g_rects.size()" <<g_rects.size() <<std::endl;
    if(g_rects.size() ==0 && r_rects.size()==0 ){
        return;
    }

    if(bInit ==false){
        hbrush_hollow = (HBRUSH)GetStockObject(HOLLOW_BRUSH);
        hpen_red = CreatePen(PS_SOLID, 5, RGB(255, 0, 0));   // 创建蓝色5像素宽度的实线画笔
        hpen_green = CreatePen(PS_SOLID, 5, RGB(0, 255, 0)); // 创建蓝色5像素宽度的实线画笔
        bInit = true;
    }

    HBRUSH hbrush_old = (HBRUSH)SelectObject(hdc, hbrush_hollow);
    HPEN hpen_old = (HPEN)SelectObject(hdc, hpen_red);
    for(int i=0;i<r_rects.size();i++){
        Rectangle(hdc, r_rects[i].left, r_rects[i].top, r_rects[i].right,r_rects[i].bottom);
    }

    SelectObject(hdc, hpen_green);
    for(int i=0;i<g_rects.size();i++){
        Rectangle(hdc, g_rects[i].left, g_rects[i].top, g_rects[i].right,g_rects[i].bottom);
    }

    SelectObject(hdc, hpen_old);
    SelectObject(hdc, hbrush_old);
#endif

}

void MainWindow::addString()
{
    HWND hWnd = (HWND)ui->label->winId();
    HDC hdc = GetDC(hWnd);
    bool isok;

    //fDrawFun g_cbDrawFun;
    isok = NET_DVR_RigisterDrawFun(IRealPlayHandle ,stringCallBack , 0);
    if(isok == false){
        LOG(ERROR) << "NET_DVR_RigisterDrawFun error,error number is :" << NET_DVR_GetLastError() <<std::endl;
        return;
    }
}

void MainWindow::resizeEvent(QResizeEvent *)
{
    //view->resize(this->size());
}

void MainWindow::on_login_clicked()
{
    bool ok;
    if(ui->IP_add_2->text() != "" &&\
                                         ui->User_2->text() != ""  &&\
              ui->Password_2->text() != "" &&\
              ui->Port_2->text() !=""){
        char devip[64] ={};
        char user[64] ={};
        char password[64] ={};
        memcpy(devip,ui->IP_add_2->text().toLatin1().data(),ui->IP_add_2->text().toLatin1().length());
        memcpy(user,ui->User_2->text().toLatin1().data(),ui->User_2->text().toLatin1().length());
        memcpy(password,ui->Password_2->text().toLatin1().data(),ui->Password_2->text().toLatin1().length());
        int port = ui->Port_2->text().toInt(&ok,10);

        /*        LOG(INFO) << "ui->IP_add_2->text(): " <<ui->IP_add_2->text()<< std::endl;
         LOG(INFO) << "ui->User_2->text(): " << ui->User_2->text() << std::endl;
         LOG(INFO) << "ui->Password_2->text(): " << ui->Password_2->text() << std::endl;
         LOG(INFO) << "ui->Port_2->text(): " << ui->Port_2->text() << std::endl;*/

        LOG(INFO) << "devip: " << devip << std::endl;
        LOG(INFO) << "port: " << port << std::endl;
        LOG(INFO) << "user: " << user << std::endl;
        LOG(INFO) << "password: " << password << std::endl;
        userID = NET_DVR_Login_V30(devip,port,user,password,&DeviceInfoTmp);
        if(userID<0){
            LOG(INFO) << "NET_DVR_Login_V30 error;" << "error number is " << NET_DVR_GetLastError();
            return;
        }
        LOG(INFO) << "NET_DVR_Login_V30 success userID " << userID<< std::endl;
    }
}

void MainWindow::on_start_play_clicked()
{
    HWND hWnd = (HWND)ui->label->winId();
    NET_DVR_PREVIEWINFO struPlayInfo={};
    struPlayInfo.dwStreamType = 1;
    IRealPlayHandle = Realplay::play(userID,hWnd,struPlayInfo);
    addString();
}

void MainWindow::on_stop_play_clicked()
{
    Realplay::closeplay(IRealPlayHandle);
    ui->label->clear();
}

void MainWindow::on_pushButton_clicked()
{
    this->showFullScreen();
}

void MainWindow::on_pushButton_2_clicked()
{
    view->reload();
}

void MainWindow::on_pushButton_3_clicked()
{
    close_hide_all();
    //设置video居中，可能需要多次
    this->t->start(50);
    connect(t, &QTimer::timeout, [=]{
        int img_width =(SCREEN_WIDTH -  this->ui->label->width())/2;
        this->ui->label->move(img_width, 0);

//        this->label1->move(img_width, 0);
//        this->label1->setVisible(true);
//        this->showCarStopRect();
        LOG(INFO) << "img_width " << img_width<< std::endl;

//        this->ui->label_2->move(0, 0);
//        this->ui->label_3->move(this->ui->label->width()+img_width, 0);

        //this->ui->label_2->setVisible(true);
        //this->ui->label_3->setVisible(true);
        if(this->ui->label->geometry().x() == img_width){
            t->stop();
        }
    });
}

void MainWindow::on_pushButton_4_clicked()
{
#if 0
    static int x=10;
    x+=10;
    std::vector<QRect> rects;
    QRect rect(x,0,100,100);
    rects.push_back(rect);

    std::vector<QColor> colors;
    QColor color(Qt::yellow);
    colors.push_back(color);
    emit videoDrawSignal(rects,colors);
#endif
    env_disp_server.send_rect_test();

}

void MainWindow::showCarStopRect()
{
    std::vector<QRect> rects;
    rects.push_back(carStopRect);
    std::vector<QColor> colors;
    QColor color(Qt::yellow);
    colors.push_back(color);
    emit videoDrawSignal(rects,colors);
}

int MainWindow::init_haikang_sdk()
{
    /*sdk初始化*/
    bool isok = NET_DVR_Init();
    if(isok == false){
        LOG(INFO) << "NET_DVR_Init error;error number is " <<NET_DVR_GetLastError();
        return -1;
    }
    //设置连接时间与重连时间
    NET_DVR_SetConnectTime(2000, 1);
    NET_DVR_SetReconnect(10000, true);
    return 0;
}

int MainWindow::init_web_view()
{
    //1、引入布局，用于存放QWebengineView；
    view = new SWebEngineView(this);
    //2、指定的父项ui->frame是在ui界面引入了一个QFrame,用于加载QWebengineView。
    QStackedLayout *layout =new QStackedLayout(ui->frame);
    //3、设置frame的布局为layout。
    ui->frame->setLayout(layout);
    layout->addWidget(view);

    view->load(strWebUrl);
    //view->load(QUrl("https://www.baidu.com/"));
    view->showFullScreen();
    //ui->pushButton->setDisabled(true);
    return 0;
}

int MainWindow::init_pic_view()
{
    QImage Img;
    Img.load(":/new/prefix1/pic/Dingtalk_20231026143615.png");
    QSize img_size((SCREEN_WIDTH - this->ui->label->width())/2, this->ui->label->height());
    ui->label_2->setPixmap(QPixmap::fromImage(Img.scaled(img_size)));

    Img.load(":/new/prefix1/pic/Dingtalk_20231026145025.png");
    ui->label_3->setPixmap(QPixmap::fromImage(Img.scaled(img_size)));
    this->ui->label_2->setVisible(false);
    this->ui->label_3->setVisible(false);
    return 0;
}

int MainWindow::init_video_draw()
{
    label1 = new QLabel(this);
    ui->label->setVisible(true);

    QImage img1(QSize(640,360),QImage::Format_RGBA8888);
    img1.fill(QColor(0,0,0,0));
    label1->setPixmap(QPixmap::fromImage(img1));
    label1->setGeometry(ui->label->geometry());
    label1->setVisible(false);
    connect(&env_disp_server,
            SIGNAL(videoDrawSignal(std::vector<QRect>, std::vector<QColor>)),
            this,
            SLOT(videoDrawSlot(std::vector<QRect> , std::vector<QColor> )));
    return 0;
}

void MainWindow::close_hide_all()
{
#if 1
    //关闭所有按钮
    ui->login->setDisabled(true);
    ui->start_play->setDisabled(true);
    ui->stop_play->setDisabled(true);
    ui->pushButton->setDisabled(true);
    ui->pushButton_2->setDisabled(true);
    ui->pushButton_3->setDisabled(true);

    //隐藏所有按钮
    ui->IP_add->setVisible(false);
    ui->Port->setVisible(false);
    ui->User->setVisible(false);
    ui->Password->setVisible(false);

    ui->IP_add_2->setVisible(false);
    ui->Port_2->setVisible(false);
    ui->User_2->setVisible(false);
    ui->Password_2->setVisible(false);

    ui->login->setVisible(false);
    ui->start_play->setVisible(false);
    ui->stop_play->setVisible(false);
    ui->pushButton->setVisible(false);
    ui->pushButton_2->setVisible(false);
    ui->pushButton_3->setVisible(false);
    ui->pushButton_4->setVisible(false);

#endif
}

void MainWindow::loadSysIni()
{
#if 1
    QFileInfo fileInfo(CONFIG_FILE_PATH);
    if(fileInfo.isFile())
    {
        QSettings setting(CONFIG_FILE_PATH, QSettings::IniFormat);
        setting.setIniCodec("utf-8");
        strWebUrl = setting.value("/Web/url").toString();
        int x = setting.value("/CarStop/x").toInt();
        int y = setting.value("/CarStop/y").toInt();
        int w = setting.value("/CarStop/w").toInt();
        int h = setting.value("/CarStop/h").toInt();
        carStopRect = QRect(x,y,w,h);
    }
#endif
}

void MainWindow::videoDrawSlot(std::vector<QRect> rects, std::vector<QColor> colors)
{
    QImage image(QSize(640,360),QImage::Format_RGBA8888);
    image.fill(QColor(0,0,0,0));

    QPainter painter(&image);
    for(int i=0;i<rects.size();i++){
        QPen pen;
        pen.setColor(colors[i]);
        pen.setWidth(3);
        painter.setPen(pen);
        painter.drawRect(rects[i]);
    }
    label1->setPixmap(QPixmap::fromImage(image));
}
